package com.ky.manage.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;

import com.ky.manage.constant.OverallData;
import com.ky.manage.permission.AndPermissionUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dell on 2018/6/11.
 * 读取word的工具类
 */

public class FileUtil {
    private final static String TAG = "FileUtil";
    private static final long G_SIZE = 1024 * 1024 * 1024;

    public static String getFileName(String pathandname) {
        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return "";
        }
    }

    //检查该文件是否存在  否则创建
    public static String createMkdirsFile(String dir_name, String file_name) {
        try {
            File dirFile = new File(dir_name);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            if (!TextUtils.isEmpty(file_name)) {
                File myFile = new File(dir_name + file_name);
                if (!myFile.exists()) {
                    myFile.createNewFile();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dir_name + file_name;
    }

    /**
     * 获取路径下的所有文件/文件夹
     *
     * @param directoryPath  需要遍历的文件夹路径
     * @param isAddDirectory 是否将子文件夹的路径也添加到list集合中
     * @return
     */
    public static List<String> getDirAllFile(String directoryPath, boolean isAddDirectory) {
        List<String> list = new ArrayList<>();
        File baseFile = new File(directoryPath);
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }
        File[] files = baseFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if (isAddDirectory) {
                    list.add(file.getAbsolutePath());
                }
                list.addAll(getDirAllFile(file.getAbsolutePath(), isAddDirectory));
            } else {
                list.add(file.getAbsolutePath());
            }
        }
        return list;
    }

    /**
     * 重命名文件
     *
     * @param oldPath 原来的文件地址
     * @param newPath 新的文件地址
     */
    public static boolean renameFile(String oldPath, String newPath) {
        File oleFile = new File(oldPath);
        File newFile = new File(newPath);
        //执行重命名
        return oleFile.renameTo(newFile);
    }

    /**
     * 复制文件并删除源文件
     *
     * @param oldFilePath String 原文件路径 如：c:/fqf.txt
     * @param newFilePath String 复制后路径 如：f:/fqf.txt
     * @return
     */
    public static boolean copyFileAndDelete(String oldFilePath, String newFilePath, boolean append) {
        if (TextUtils.isEmpty(oldFilePath) || TextUtils.isEmpty(newFilePath) || newFilePath.equals(oldFilePath))
            return true;
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            File oldFile = new File(oldFilePath);
            //如果原文件不存在
            if (!oldFile.exists()) {
                return true;
            }
            //复制到新文件中去
            String dirPath = newFilePath.substring(0, newFilePath.lastIndexOf("/") + 1);
            String fileName = newFilePath.substring(newFilePath.lastIndexOf("/") + 1, newFilePath.length());
            newFilePath = FileUtil.createMkdirsFile(dirPath, fileName);
            File newFile = new File(newFilePath);
            //获得原文件流
            inputStream = new FileInputStream(oldFile);
            byte[] data = new byte[1024];
            //输出流
            outputStream = new FileOutputStream(newFile, append);
            //开始处理流
            int c;
            while ((c = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, c);
            }

            inputStream.close();
            outputStream.close();
            //删除老文件
            if (newFile.exists()) {
                oldFile.delete();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
//            CustomLogUtils.d("zhaoyan", "copyFileAndDelete e1 = " + e.toString());
            return false;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
//                CustomLogUtils.d("zhaoyan", "copyFileAndDelete e2 = " + e.toString());
            }
        }
    }

    /**
     * 保存签字图片
     *
     * @param bitmap
     */
    public static String saveBitmap(Bitmap bitmap, String dir, String name) {
        try {
            File dirFile = new File(dir);
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            File file = new File(dir + name);
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            return file.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 删除所有文件: 默认不删除目录
     *
     * @param
     */
    public static void deleteFile(File file) {
        if (null == file || !file.exists()) {
            return;
        }
        deleteFile(file, false);
    }

    /**
     * 删除文件不包含文件目录
     *
     * @param file
     * @param delDirectory
     */
    public static void deleteFile(File file, boolean delDirectory) {
        if (null == file || !file.exists()) {
            return;
        }
        try {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (null != files && files.length > 0) {
                    for (File file1 : files) {
                        deleteFile(file1, delDirectory);
                    }
                }
                if (delDirectory) {
                    file.delete();
                }
            } else {
                file.delete();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 删除所有文件
     *
     * @param
     */
    public static void deleteFile(File file, ArrayList<File> excludeFileList) {
        if (null == file || !file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null != files && files.length > 0) {
                for (File file1 : files) {
                    deleteFile(file1, excludeFileList);
                }
            }
        } else if (file.exists()) {
            try {
                if (null != excludeFileList && !excludeFileList.isEmpty()) {
                    boolean needDel = true;
                    for (File file1 : excludeFileList) {
                        if (null != file1 && file1.exists() && file1.getAbsolutePath().equals(file.getAbsolutePath())) {
                            //不需要删除文件
                            needDel = false;
                            break;
                        }
                    }
                    if (needDel) {
                        file.delete();
                    }
                } else {
                    file.delete();
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 获取文件夹大小
     *
     * @param file File实例
     * @return long
     */
    public static long getFolderSize(File file) {

        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);

                } else {
                    size = size + fileList[i].length();

                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //return size/1048576;
        return size;
    }

    /**
     * 获取文件大小
     *
     * @param fileSize 附件文件大小，多个以 | 分开
     * @return
     */
    public static long pareFileSizeList(String fileSize) {
        long fileSizeByte = 0;
        if (!TextUtils.isEmpty(fileSize)) {
            String[] fileSizeArr = fileSize.split("\\|");
            if (fileSizeArr.length > 1) {
                for (String size : fileSizeArr) {
                    try {
                        fileSizeByte += Long.parseLong(size);
                    } catch (NumberFormatException e) {
                    }
                }
            } else {
                try {
                    fileSizeByte += Long.parseLong(fileSize);
                } catch (NumberFormatException e) {
                }
            }
        }
        return fileSizeByte;
    }

    /**
     * 添加文件路径
     *
     * @param path
     * @return
     */
    public static List<String> addFiles(String path) {
        List<String> files = new ArrayList<>();
        if (!TextUtils.isEmpty(path)) {
            if (path.split("\\|").length > 1) {
                for (int j = 0; j < path.split("\\|").length; j++) {
                    String src = path.split("\\|")[j];
                    files.add(src);
                }
            } else {
                files.add(path);
            }
        }
        return files;
    }

    /**
     * 添加本地文件路径
     *
     * @param path
     * @return
     */
    public static String addLocalFiles(String path) {
        StringBuilder loaclFiles = new StringBuilder();
        List<String> fileNames = addFiles(path);
        if (fileNames != null) {
            for (int i = 0; i < fileNames.size(); i++) {
                loaclFiles.append(OverallData.sdkPath).append("lxkjAnnouncement").append(fileNames.get(i).substring(fileNames.get(i).lastIndexOf("/"), fileNames.get(i).length())).append(",");


            }
        }
        return loaclFiles.toString();
    }

    public static byte[] getFileByte(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            int buffSize = 1024;
            byte[] buffer = new byte[buffSize];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buffSize))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param context
     * @param srcPath such as "playback"
     * @param dstPath such as "/storage/emulated/0/lxrecord"
     */
    public static void copyAssetsToDst(Context context, String srcPath, String dstPath) {
        if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(dstPath)) {
            return;
        }
        try {
            String[] fileNames = context.getAssets().list(srcPath);
            if (fileNames.length > 0) {
                for (String string : fileNames) {
                    copyAssetsToFile(context, srcPath + File.separator + string,
                            dstPath + File.separator + string);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getFilePathByName(Context context, String srcPath, String fileName) {
        if (TextUtils.isEmpty(fileName) || TextUtils.isEmpty(srcPath)) return "";
        try {
            File file = new File(srcPath);
            if (!file.exists() && !file.isDirectory()) {
                return "";
            }
            File[] fileNames = file.listFiles();
            if (fileNames.length > 0) {
                for (File file1 : fileNames) {
                    if (file1.getName().equals(fileName) || file1.getName().indexOf(fileName) != -1) {
                        return file1.getAbsolutePath();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param context
     * @param srcFilePath such as "traindata.txt"
     * @param dstFilePath such as "/storage/emulated/0/lxrecord/traindata.txt"
     */
    public static boolean copyAssetsToFile(Context context, String srcFilePath, String dstFilePath) {
        if (TextUtils.isEmpty(srcFilePath) || TextUtils.isEmpty(dstFilePath)) {
            return false;
        }
        InputStream is = null;
        FileOutputStream fos = null;
        boolean copyResult = true;
        try {
            String dstDirectory = dstFilePath.substring(0, dstFilePath.lastIndexOf("/"));
            File directory = new File(dstDirectory);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            File outFile = new File(dstFilePath);
            is = context.getAssets().open(srcFilePath);
            fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
        } catch (IOException e) {
            e.printStackTrace();
            copyResult = false;
        } catch (Exception e) {
            e.printStackTrace();
            copyResult = false;
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != fos) {
                    fos.flush();
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                copyResult = false;
            } catch (Exception e) {
                e.printStackTrace();
                copyResult = false;
            }
        }
        return copyResult;
    }

    public static String getFileNameWithSuffix(String filePath) {
        File file = new File(filePath);
        return file.exists() ? file.getName() : "";
    }

    public static String getFileNameWithNoSuffix(String filePath) {
        String fileName = getFileNameWithSuffix(filePath);
        return TextUtils.isEmpty(fileName) ? "" : fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(0, fileName.lastIndexOf("."));
    }

    public static void createFileWithPath(String filePath) {
        //复制到新文件中去
        String dirPath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
        FileUtil.createMkdirsFile(dirPath, fileName);
    }

    public static void mergeFilesToDst(List<String> fileList, String dstFilePath) {
        int index = fileList.indexOf(dstFilePath);
        Log.d(TAG, "mergeFilesToDst: index" + index);
        long size = 0;
        for (int i = 0; i < fileList.size(); i++) {
            long fileSize = new File(fileList.get(i)).length();
            if (i == index) {
                size = fileSize;
                Log.d(TAG, "mergeFilesToDst: sameFileIndex: " + index + " size: " + size);
                continue;
            }
            copyFileAndDelete(fileList.get(i), dstFilePath, size);
            size = size + fileSize;
            Log.d(TAG, "mergeFilesToDst: startFileIndex" + size);
        }
    }

    public static boolean mergeFiles(List<String> fileList, String dstFilePath) {
        String tempDstFilePath = dstFilePath + ".temp";
        File file = new File(tempDstFilePath);
        if (file.exists()) {
            file.delete();
        }
        for (int i = 0; i < fileList.size(); i++) {
            boolean mergeResult = copyFileAndDelete(fileList.get(i), tempDstFilePath, true);
            if (!mergeResult) {
                if (file.exists()) {
                    file.delete();
                }
                return false;
            }
        }
        return copyFileAndDelete(tempDstFilePath, dstFilePath, false);
    }

    /**
     * 复制文件并删除源文件
     *
     * @param oldFilePath String 原文件路径 如：c:/fqf.txt
     * @param newFilePath String 复制后路径 如：f:/fqf.txt
     * @return
     */
    public static boolean copyFileAndDelete(String oldFilePath, String newFilePath, long seekIndex) {
        FileInputStream inputStream = null;
        RandomAccessFile randomAccessFile = null;
        try {
            File oldFile = new File(oldFilePath);
            //如果原文件不存在
            if (!oldFile.exists()) {
                return false;
            }
            //复制到新文件中去
            String dirPath = newFilePath.substring(0, newFilePath.lastIndexOf("/") + 1);
            String fileName = newFilePath.substring(newFilePath.lastIndexOf("/") + 1, newFilePath.length());
            newFilePath = FileUtil.createMkdirsFile(dirPath, fileName);
            File newFile = new File(newFilePath);
            //获得原文件流
            inputStream = new FileInputStream(oldFile);
            byte[] data = new byte[1024];
            //输出流
            randomAccessFile = new RandomAccessFile(newFile, "rws");
            //开始处理流
            randomAccessFile.seek(seekIndex);
            //输出流
            //开始处理流
            int c;
            while ((c = inputStream.read(data)) != -1) {
                randomAccessFile.write(data, 0, c);
            }
            inputStream.close();
            randomAccessFile.close();
            //删除老文件
            if (newFile.exists()) {
                oldFile.delete();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 拷贝文件目录
     *
     * @param srcPath
     * @param dstPath
     */
    public static boolean copyFileDirectory(String srcPath, String dstPath) {
//        CustomLogUtils.d("zhaoyan123", "copyFileList srcPath = " + srcPath + ", dstPath = " + dstPath);
        if (!AndPermissionUtils.getInstance().hasStoragePermission()) {
            return false;
        }
        File srcDirectory = new File(srcPath);
        if (!srcDirectory.exists()) {
            return false;
        }
        File[] srcFileList = srcDirectory.listFiles();
        if (null == srcFileList || srcFileList.length == 0) {
            return false;
        }
        File dstDirectory = new File(dstPath);
        if (!dstDirectory.exists()) {
            dstDirectory.mkdirs();
        }
        boolean result = true;
        try {
            for (File file : srcFileList) {
                result = copyFile(srcPath + (srcPath.endsWith("/") ? "" : "/") + file.getName(),
                        dstPath + (dstPath.endsWith("/") ? "" : "/") + file.getName());
            }
        } catch (Exception e) {
//            CustomLogUtils.d("zhaoyan123", "copyFileList e = " + e.toString());
            e.printStackTrace();
            result = false;
        }
        //只要有一个成功认为拷贝成功
        return result;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath$Name String 原文件路径+文件名 如：data/user/0/com.test/files/abc.txt
     * @param newPath$Name String 复制后路径+文件名 如：data/user/0/com.test/cache/abc.txt
     * @return <code>true</code> if and only if the file was copied;
     * <code>false</code> otherwise
     */
    public static boolean copyFile(String oldPath$Name, String newPath$Name) {
        boolean copySuccess = false;
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        if (TextUtils.isEmpty(oldPath$Name) || TextUtils.isEmpty(newPath$Name)) {
            return copySuccess;
        }
        try {
            File oldFile = new File(oldPath$Name);
            File newFile = new File(newPath$Name);
            if (!oldFile.exists()) {
                return copySuccess;
            } else if (!oldFile.isFile()) {
                return copySuccess;
            } else if (!oldFile.canRead()) {
                return copySuccess;
            }
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            if (newFile.exists()) {
                try {
                    newFile.delete();
                } catch (Exception e) {
                    //
                }
            }
            fileInputStream = new FileInputStream(oldPath$Name);
            fileOutputStream = new FileOutputStream(newPath$Name);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            copySuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
            copySuccess = false;
        } finally {
            try {
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
                if (null != fileOutputStream) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (IOException e) {

            } catch (Exception e) {

            }
        }
        return copySuccess;
    }

    /**
     * 当文件路径不存在时候创建文件夹路径
     *
     * @param filePathWithName
     */
    public static synchronized void checkDirectory(String filePathWithName) {
        int index = filePathWithName.lastIndexOf("/");
        if (index == -1 || index >= filePathWithName.length() - 1) return;
        String directory = filePathWithName.substring(0, index + 1);
        File file = new File(directory);
        file.mkdirs();
    }

    //文件拷贝
    //要复制的目录下的所有非子目录(文件夹)文件拷贝
    public int copySdcardFile(String fromFile, String toFile) {
        try {
            InputStream fosfrom = new FileInputStream(fromFile);
            OutputStream fosto = new FileOutputStream(toFile);
            byte[] bt = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosfrom.close();
            fosto.close();
            new File(fromFile).delete();
            return 0;

        } catch (Exception ex) {
            return -1;
        }
    }

    /**
     * 读取本地文件
     * @param filePathName
     * @return
     */
    public static String readFile(String filePathName) {
        if (TextUtils.isEmpty(filePathName)) {
            return "";
        }
        File file = new File(filePathName);
        if (!file.exists()) {
            return "";
        }
        StringBuffer stringBuffer = new StringBuffer();
        FileInputStream fileInputStream = null;
        try {
            // 打开文件输入流
            fileInputStream = new FileInputStream(filePathName);
            byte[] buffer = new byte[1024];
            int len = fileInputStream.read(buffer);
            // 读取文件内容
            while (len > 0) {
                stringBuffer.append(new String(buffer, 0, len));
                // 继续将数据放到buffer中
                len = fileInputStream.read(buffer);
            }
        } catch (Exception e) {

        } finally {
            if (null != fileInputStream) {
                // 关闭输入流
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuffer.toString();
    }
}
